/***********************************************************************************
Copy right:	    Coffee Tech.
Author:         jiaoyue
Date:           2022-04-08
Description:    mqtt通信封装
***********************************************************************************/

#include "mqtt.h"

//下面的按需修改
#define MQTT_ADDR "192.168.28.239"
#define MQTT_PORT 1883
#define CLIENT_ID "hqyj_mqtt"

/*******************下面的别动***************************/
#define QOS         1
#define TIMEOUT     10000L

//函数声明
extern int handle_msg_from_simulation(const char *topic_name, const char *payload);

static MQTTClient_deliveryToken token;
static MQTTClient client;

void delivered(void *context, MQTTClient_deliveryToken dt)
{
    // printf("Message with token value %d delivery confirmed\n", dt);
    token = dt;
}

int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    //    LOGD("Message arrived");
    //    LOGD("    topic:%s", topicName);
    //    LOGD("    message:%s", message->payload);
    handle_msg_from_simulation(topicName, message->payload);

    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return 1;
}

void connlost(void *context, char *cause)
{
    printf("\nConnection lost\n");
    printf("     cause: %s\n", cause);
}

int mqtt_publish(const char *topic, char *msg)
{
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    pubmsg.payload = msg;
    pubmsg.payloadlen = (int)strlen(msg);
    pubmsg.qos = QOS;
    pubmsg.retained = 0;
    return MQTTClient_publishMessage(client, topic, &pubmsg, &token);
}

/**
 * @brief 订阅某个主题
 * @param topic 主题名字
 * @return 0 -1
 */
int mqtt_subscribe(const char *topic)
{
    return MQTTClient_subscribe(client, topic, QOS);
}


int mqtt_init()
{
    //先解析出mqtt的地址和端口
    char mqtt_addr[256] = {0};

    sprintf(mqtt_addr, "tcp://%s:%d", MQTT_ADDR, MQTT_PORT);
    printf("mqtt_addr = %s\n", mqtt_addr);

    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    int rc;

    MQTTClient_create(&client, mqtt_addr, CLIENT_ID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;

    MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);

    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        return -1;
    }
    printf("mqtt connect success\n");

    return 0;
}
